#!/usr/bin/perl -Tw
## Coding by XAD of Nightfall
## Copyright by SpheraIT
## GPL Source

use DBI;

open(FILE, "/etc/amportal.conf") || die "Failed to open amportal.conf\n";
while (<FILE>) {
    chomp;                  # no newline
    s/#.*//;                # no comments
    s/^\s+//;               # no leading white
    s/\s+$//;               # no trailing white
    next unless length;     # anything left?
    my ($var, $value) = split(/\s*=\s*/, $_, 2);
    $User_Preferences{$var} = $value;
}
close(FILE);

$smtpconfig_table_name = "smtpconfig";
$smtpconfig_conf = "/etc/mail/voipermail.conf";
$smtpconfig_conf_2 = "/etc/mail/authinfo";
$smtpconfig_conf_3 = "/etc/mail/genericstable";
$hostname = $User_Preferences{"AMPDBHOST"};
$database = $User_Preferences{"AMPDBNAME"};
$username = $User_Preferences{"AMPDBUSER"};
$password = $User_Preferences{"AMPDBPASS"};


open EXTEN, ">$smtpconfig_conf" or die "Cannot create/overwrite voipermail.conf file: $smtpconfig_conf\n";
open EXTEN_2, ">$smtpconfig_conf_2" or die "Cannot create/overwrite authinfo file: $smtpconfig_conf_2\n";
open EXTEN_3, ">$smtpconfig_conf_3" or die "Cannot create/overwrite genericstable file: $smtpconfig_conf_2\n";

$dbh = DBI->connect("dbi:mysql:dbname=$database;host=$hostname", "$username", "$password");
$statement = "SELECT * from $smtpconfig_table_name";
my $result = $dbh->selectall_arrayref($statement);
unless ($result) {
  print "dbh->selectall_arrayref($statement) failed!\n";
  print "DBI::err=[$DBI::err]\n";
  print "DBI::errstr=[$DBI::errstr]\n";
  exit;
}
my @resultSet = @{$result};
if ( $#resultSet > -1 ) {

    foreach $row (@{ $result }) {
        my @result = @{ $row };

        $smtplogin = $result[0];
        $smtppassword = $result[1];
        $smtphost = $result[2];
        $masquarade = $result[3];

        print EXTEN "define(`SMART_HOST',`$smtphost')\n";
        print EXTEN "MASQUERADE_AS(`$masquarade')dnl\n";
        print EXTEN "MASQUERADE_DOMAIN(`$masquarade')dnl\n";

        if ( $smtplogin eq "" and $smtppassword eq "") {

            print EXTEN "dnl FEATURE(`authinfo',`hash /etc/mail/authinfo.db')dnl\n";

                } else {

                    print EXTEN "FEATURE(`authinfo',`hash /etc/mail/authinfo.db')dnl\n";

                }
        }

    foreach $row (@{ $result }) {
        my @result = @{ $row };

        $smtplogin = $result[0];
        $smtppassword = $result[1];

        print EXTEN_2 "AuthInfo: \"U:$smtplogin\" \"P:$smtppassword\"\n";

        }

    foreach $row (@{ $result }) {
        my @result = @{ $row };

        $fromemail = $result[4];

        if ( $fromemail eq "" ) {

            print EXTEN_3 "";

        } else {

                print EXTEN_3 "root $fromemail\n";
								print EXTEN_3 "asterisk $fromemail\n";

        }

     }

}

exit 0;
